package com.fancyy.scm.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableBoolean;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.fancyy.scm.BRActivityManager;
import com.fancyy.scm.BRApplication;
import com.fancyy.scm.R;
import com.fancyy.scm.base.annotation.Layout;
import com.fancyy.scm.base.annotation.Translucent;
import com.fancyy.scm.bean.UserInfo;
import com.fancyy.scm.util.SoundUtils;
import com.fancyy.scm.util.StatusBarUtil;
import com.fancyy.scm.util.ToastUtil;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 所有Activity页面的抽象父类
 *
 * @param <DataBinding> 数据绑定者
 */
public abstract class BaseActivity<DataBinding extends ViewDataBinding> extends Activity implements EMDKManager.EMDKListener,
        Scanner.DataListener, Scanner.StatusListener, BarcodeManager.ScannerConnectionListener {
    //private SoundPool soundPool;
    boolean needScan = false;

    //用于判断是否为PDA设备，如果是PDA设备即可以调用扫码，不是则调用摄像头
    boolean isPDA = false;

    public void setNeedScan(boolean needScan) {
        this.needScan = needScan;
    }

    public boolean getPDA()
    {
        return isPDA;
    }

    /**
     * 扫码相关
     */
    //EMDK服务
    private EMDKManager emdkManager = null;
    //扫码服务
    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;
    private List<ScannerInfo> deviceList = null;
    private boolean bContinuousMode;//是否持续扫描.
    private int scannerIndex = 0; // 保留选定的扫描器


    public ObservableBoolean isRefreshing = new ObservableBoolean(false);

    public SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            doOnRefresh();
        }
    };

    public void doOnRefresh() {

    }

    public void doLoadMore() {

    }

    public void playSound(int soundRaw) {
        /*if (soundPool != null)
            soundPool.play(1, 1, 1, 0, 0, 1);*/
        SoundUtils.ShareManager().PlaySound(this, soundRaw);
    }


    private DataBinding dataBinding;

    private boolean onCreateInvoke = false;

    private boolean autoChangeStatusBar = true;

    //点击返回键时间
    private long mLastClickBackTime = 0;
    private boolean mDoubleFinish = false;

    public void setAutoChangeStatusBar(boolean autoChangeStatusBar) {
        this.autoChangeStatusBar = autoChangeStatusBar;
    }

    /**
     * 绑定一个布局(请在onCreate()方法之前调用)
     * 使用Layout注解将覆盖此方法
     *
     * @param layoutResID
     * @param title
     * @param rightButtonText
     */
    public void bindLayout(int layoutResID, String title, String rightButtonText) {
        bindLayout(layoutResID, title, rightButtonText, -1);
    }

    /**
     * 绑定一个布局(请在onCreate()方法之前调用)
     * 使用Layout注解将覆盖此方法
     *
     * @param layoutResID
     * @param title
     * @param rightButtonResId
     */
    public void bindLayout(int layoutResID, String title,
                           String rightButtonText, int rightButtonResId) {
        if (onCreateInvoke == true) {
            throw new RuntimeException("bindLayout方法必须在onCreate方法之前调用");
        }
        dataBinding = DataBindingUtil.setContentView(this, layoutResID);
//        TextView titleView = (TextView) findViewById(R.id.actionbarTitle);
//        if (titleView != null) {
//            titleView.setText(title);
//        }
//        ImageView rightButtonImageView = (ImageView) findViewById(R.id.imageButton);
//        if (rightButtonImageView != null && rightButtonResId > 0) {
//            rightButtonImageView.setImageResource(rightButtonResId);
//            rightButtonImageView.setOnClickListener(v -> onRightButtonClick());
//        }
//        TextView rightButtonTextView = (TextView) findViewById(R.id.textButton);
//        if (rightButtonTextView != null && !TextUtils.isEmpty(rightButtonText)) {
//            rightButtonTextView.setText(rightButtonText);
//            rightButtonTextView.setOnClickListener(v -> onRightButtonClick());
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        BRActivityManager.addActivity(this);
        super.onCreate(savedInstanceState);

        // 布局注入
        Layout layout = getClass().getAnnotation(Layout.class);
        if (layout != null) {
            bindLayout(layout.value(), layout.title(),
                    layout.rightButton(), layout.rightButtonRes());
        }
        onCreateInvoke = true;

        // 绑定activity对象到布局
        bindViewModelToUI();

        // 透明状态栏
        handleStatusBar();


        if (needScan) {
            /*soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 5);
            soundPool.load(this, R.raw.error, 1);*/
        }

    }

    protected void handleStatusBar() {
        Translucent translucentAnnotation = getClass().getAnnotation(Translucent.class);
        if (translucentAnnotation != null && translucentAnnotation.value()) {
            StatusBarUtil.setTranslucent(this);
        } else {
            // 非透明状态栏采用黑色风格 + 白色statusBar
            if (autoChangeStatusBar) {
                StatusBarUtil.setTranslucent(this);
                StatusBarUtil.setColorWithColorIntValue(this, Color.TRANSPARENT);
                boolean support = StatusBarUtil.setDarkStyleTitleBar(this);
                View rootView = ((getWindow().getDecorView().findViewById(android.R.id.content)));
                rootView.setPadding(0, StatusBarUtil.getStatusBarHeight(this), 0, 0);
//                if (support) {
//                    rootView.setBackgroundColor(getResources().getColor(R.color.nhs_bg_white));
//                } else {
//                    rootView.setBackgroundColor(getResources().getColor(R.color.nhs_bg_gray2));
//                }
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needScan) {
            //启动EMDK服务
            deviceList = new ArrayList<>();

            try {
                EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
                if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
                    Log.i("BaseActivity", "启动 EMDK 失败");
                    Toast.makeText(this, "start scanning emdk failed", Toast.LENGTH_SHORT).show();
                    return;
                }
                isPDA = true;
            }
            catch (Exception ex)
            {
                isPDA = false;
            }
        }
        if (needScan && isPDA)
            openScan();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (needScan && isPDA)
            closeScan();
        if (needScan && isPDA) {
            // De-initialize扫描仪
            deInitScanner();
            // 移除连接监听器
            if (barcodeManager != null) {
                barcodeManager.removeConnectionListener(this);
                barcodeManager = null;
            }
            // 释放所有的资源
            if (emdkManager != null) {
                emdkManager.release();
                emdkManager = null;

            }
        }
    }
    /**
     * 开启扫码
     */
    public void openScan() {
        /**
         * 扫码相关
         */
        // 获取条形码管理器资源
        if (emdkManager != null) {
            barcodeManager = (BarcodeManager) emdkManager.getInstance(EMDKManager.FEATURE_TYPE
                    .BARCODE);
            //添加连接监听器
            if (barcodeManager != null) {
                barcodeManager.addConnectionListener(this);
            }
            // 初始化扫描
            initScanner();
        }
    }

    /**
     * 关闭扫码
     */
    public void closeScan() {
        /**
         * 扫码相关
         */
        // 注销扫描
        deInitScanner();
        // 移除连接监听器
        if (barcodeManager != null) {
            barcodeManager.removeConnectionListener(this);
            barcodeManager = null;
            deviceList = null;
        }
        // 释放所有的资源
        if (emdkManager != null) {
            emdkManager.release(EMDKManager.FEATURE_TYPE.BARCODE);
        }
    }

    /**
     * 打开EMDK服务
     *
     * @param emdkManager
     */
    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManager = emdkManager;
        // 获取条形码管理器资源
        barcodeManager = (BarcodeManager) emdkManager.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);
        // 添加连接监听器
        if (barcodeManager != null) {
            barcodeManager.addConnectionListener(this);
        }
        // 列举扫描设备
        if (barcodeManager != null) {
            deviceList = barcodeManager.getSupportedDevicesInfo();
        }
        //启用扫描
        startScan();
    }

    /**
     * 启动扫描
     */
    private void startScan() {
        if (scanner == null) {
            initScanner();
        }
        if (scanner != null) {
            try {
                if (scanner.isEnabled()) {
                    // 提交一个新的阅读。
                    scanner.read();
                    bContinuousMode = true;
                }

            } catch (ScannerException e) {
                Log.i("error", "startScan: Status: " + e.getMessage());
            }
        }
    }

    /**
     * 初始化扫描
     */
    private void initScanner() {
        if (scanner == null) {
            if ((deviceList != null) && (deviceList.size() != 0)) {
                scanner = barcodeManager.getDevice(deviceList.get(scannerIndex));
            } else {
                Toast.makeText(this, "Can't find the device!\n" + "Please restart the application",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    Log.i("initScanner", "initScanner: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 关闭EMDK服务调用
     */
    @Override
    public void onClosed() {
        if (emdkManager != null) {
            // 移除连接监听器
            if (barcodeManager != null) {
                barcodeManager.removeConnectionListener(this);
                barcodeManager = null;
            }
            // 释放所有的资源
            emdkManager.release();
            emdkManager = null;
        }
        Toast.makeText(this, "EMDK Error, please restart the application", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BRActivityManager.removeActivity(this);
    }


    /**
     * 注销扫描
     */
    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.cancelRead();
                scanner.disable();
            } catch (Exception e) {
                Toast.makeText(this, "Status:" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            try {
                scanner.removeDataListener(this);
                scanner.removeStatusListener(this);
            } catch (Exception e) {
                Toast.makeText(this, "Status:" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            try {
                scanner.release();
            } catch (Exception e) {
                Toast.makeText(this, "Status:" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            scanner = null;
        }
    }

    /**
     * 连接状态改变
     *
     * @param scannerInfo
     * @param connectionState
     */
    @Override
    public void onConnectionChange(ScannerInfo scannerInfo, BarcodeManager.ConnectionState
            connectionState) {
        String scannerName = "";
        String scannerNameExtScanner = scannerInfo.getFriendlyName();
        if (deviceList.size() != 0) {
            scannerName = deviceList.get(scannerIndex).getFriendlyName();
        }
        if (scannerName.equalsIgnoreCase(scannerNameExtScanner)) {
            switch (connectionState) {
                case CONNECTED:
                    initScanner();
                    break;
                case DISCONNECTED:
                    deInitScanner();
                    break;
            }
        }
    }

    /**
     * 扫描数据返回
     *
     * @param scanDataCollection
     */
    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults
                .SUCCESS)) {
            ArrayList<ScanDataCollection.ScanData> scanData = scanDataCollection.getScanData();
            for (ScanDataCollection.ScanData data : scanData) {
                final String dataString = data.getData();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        doScan(dataString);
                    }
                });
                // 只取第一个
                break;
            }
        }
    }


    /**
     * 扫描状态
     *
     * @param statusData
     */
    @Override
    public void onStatus(StatusData statusData) {
        StatusData.ScannerStates state = statusData.getState();
        switch (state) {
            case IDLE:

                if (bContinuousMode) {
                    try {
                        // 尝试连续快速地使用扫描仪(扫描间隔小于100毫秒)
                        // 可能导致扫描仪在恢复扫描之前暂停片刻。
                        // 因此，在提交下一个读之前添加一些延迟(>= 100ms)。
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        scanner.read();
                    } catch (ScannerException e) {
                        Toast.makeText(this, "Status:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    /**
     * 扫码返回
     *
     * @param data 扫码返回数据
     */
    public void doScan(String data) {};


    /**
     * 获取数据绑定对象
     *
     * @return
     */
    public DataBinding getDataBinding() {
        return dataBinding;
    }

    /**
     * 打开一个页面
     *
     * @param activityClass
     */
    public void startActivity(Class<? extends Activity> activityClass) {
        startActivity(activityClass, false);
    }

    /**
     * 打开一个页面
     * 并且设置成是否关闭当前页面
     *
     * @param activityClass
     * @param finishSelf
     */
    public void startActivity(Class<? extends Activity> activityClass, boolean finishSelf) {
        Intent intent = new Intent(this, activityClass);
        startActivity(intent);
        if (finishSelf) {
            finish();
        }
    }

    /**
     * 使得XML布局文件中可以用viewModel
     */
    private void bindViewModelToUI() {
        if (dataBinding != null) {
            // 绑定两者
            Field[] declaredFields = dataBinding.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.getType().equals(getClass())) {
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(dataBinding, this);
                    } catch (IllegalAccessException e) {
                    }
                    declaredField.setAccessible(false);
                    break;
                }
            }
        }
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public UserInfo getLoginUser() {
        return getBRApplication().getUserInfo();
    }

    /**
     * 返回控件被点击
     *
     * @param view
     */
    public void onBackButtonClick(View view) {
        finish();
    }

    /**
     * 标题栏右上角按钮
     * 子类需要重写此方法来获取该按钮被点击时的监听
     */
    public void onRightButtonClick() {
    }

    /**
     * 返回当前对象本身,简化 XXXActivity.this
     *
     * @return
     */
    public Activity self() {
        return this;
    }

    /**
     * 获取当前应用程序的全局变量
     *
     * @return
     */
    public BRApplication getBRApplication() {
        return (BRApplication) getApplication();
    }

    /**
     * 弹出一个提示信息框
     *
     * @param message
     */
    public void showToast(String message) {
        ToastUtil.showToast(this, message);
    }


    /**
     * 自动隐藏软键盘
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    /**
     * 设置是否需要点击两次退出
     *
     * @param flag
     */
    public void setDoubleClickFinish(boolean flag) {
        this.mDoubleFinish = flag;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mDoubleFinish) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                // during 2 seconds, click 'back' twice, app will exit
                if ((System.currentTimeMillis() - mLastClickBackTime) > 2000) {
                    showToast("再次点击退出");
                    mLastClickBackTime = System.currentTimeMillis();
                    return true;
                } else {
                    BRActivityManager.clear();
                }
            } else {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
